<?php

namespace app\admin\controller;

use app\BaseController;
use app\common\result\Result;
use app\model\Admin as ModelAdmin;
use app\model\Role;
use think\exception\HttpException;
use think\facade\Request;
use thans\jwt\facade\JWTAuth;

class Admin extends BaseController
{

    protected $middleware = [
        'auth' => ['except' => ['login']],
        'checkPermission' => ['except' => ['login']],
    ];

    public function index()
    {
        $admins = ModelAdmin::select();
        return $admins;
    }

    public function detail()
    {

        $payload = JWTAuth::auth();
        $uid = $payload['uid'];

        $admin = ModelAdmin::with('roles')->find($uid);
        if ($admin == null) {
            return Result::Error(400, $uid . '不存在');
        } else {

            $roles = Role::with('permissions')->find($admin->roles->id);
            $permissions = $roles->permissions;

            return Result::Success(['admin' => $admin, 'permissions' => $permissions]);
        }
    }

    public function add()
    {

        $username = Request::post('username');
        $password = Request::post('password');

        $password = password_hash($password, PASSWORD_DEFAULT);

        $roleId = Request::post('roleId');

        $hasUsername = ModelAdmin::where('username', $username)->findOrEmpty();

        if ($hasUsername->isEmpty()) {
            $admin = new ModelAdmin();
            $admin->username = $username;
            $admin->password = $password;
            $admin->roleId = $roleId;
            $admin->save();
            return Result::Success($admin);
        } else {
            throw new HttpException(500, '用户已存在');
        }
    }

    public function login()
    {

        $username = Request::post('username');
        $password = Request::post('password');

        $user = ModelAdmin::where('username', $username)->find();

        if ($user == null) {
            throw new HttpException(400, '用户不存在');
            // return Result::Error(400, '用户不存在');
        } else {
            if (password_verify($password, $user->password)) {
                // 生成token
                $token = JWTAuth::builder(['uid' => $user->id]);
                return Result::Success(['token' => 'Bearer ' . $token]);
            } else {
                throw new HttpException(500, '账号密码有错误');
            }
        }
    }
}
